/**
 * 依赖:bootstrap,ztree
 * 使用方法:
 * var memberSelector = new MemberSelector({
 *      onSelect:function(data){
 *
 *      }
 * });
 *
 *
 */

(function(mod) {
    if (typeof exports == "object" && typeof module == "object") // CommonJS
        module.exports = mod();
    else if (typeof define == "function" && define.amd) // AMD
        return define([], mod);
    else // Plain browser env
        this.MemberSelector = mod();
})(function() {

    var selectorhtml = "<div class=''><div style='width:95%;height:auto;margin:auto;border-radius:40px;'><div class='c_modal_head'id='selector_box_title'>选择人员</div><div class='c_modal_body'><div  class='c_selector_panel_box'><div class='c_selector_panel'><div class='title'><span>机构</span><span>:</span></div><div class='body'style=''><div class='selector_left'><span></span><span></span><div><ul id='treeOrg'class='ztree'></ul></div></div></div></div><div class='c_selector_panel'><div class='title'><span>人员</span><span> &nbsp;&nbsp;<input type='checkbox' name='radio' value='1' class='Checkbox'><span style='font-size:13px'>&nbsp;显示无部门人员</span></span></div><div id='user'class='body'></div></div><div class='c_selector_panel'><div class='title'><span>已选</span><span>：</span>（<span id='al-selector-count'>0</span>）</div><div id='selector'class='body'></div></div></div><div class='c_selector_panel_footer'><div id='selector-confirm'class='c_ding_btn c_ding_btn_primary'>确定</div><div class='c_ding_btn c_ding_btn_error'data-dismiss='modal'>取消</div></div></div></div></div>";
    var modalhtml = "<div style='display:none;width:auto;' class='modal fade' id='MemberSelectorModal' data-type='0' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'><div class='modal-dialog'><div class='modal-dialog' role='document'><div class='modal-content'></div></div></div></div>";

    function MemberSelector(elem,options,callback){
        //console.log(get.byId(elem));
        var option = $.extend({},defaults,options);

        var element = $(elem);
        console.log(element);

        this._init(element,option,callback);
		
    }

    //type:选择类型，0所有类型，1用户，2部门
    var defaults = {
        url : '/index.php?m=Admin&c=Organization&a=selectorTree',
        multiple:false,
        title : '选择人员',
        type : 0,
        treeSetting : {
            view: {
                selectedMulti: false, //设置是否能够同时选中多个节点
                showIcon: true, //设置是否显示节点图标
                showLine: true, //设置是否显示节点与节点之间的连线
                showTitle: true, //设置是否显示节点的title提示信息
            },
            data: {
                simpleData: {
                    enable: true, //设置是否启用简单数据格式
                    idKey: "id", //设置启用简单数据格式时id对应的属性名称
                    pidKey: "pid" //设置启用简单数据格式时parentId对应的属性名称
                }
            },
            check:{
                enable: true,  //设置是否显示checkbox复选框
                chkStyle: 'checkbox', //单选框
                radioType: "all", //对所有节点设置单选
                chkboxType:  { "Y": "", "N": "" }
            },
            callback: {
                onClick: myonClick,  //定义节点单击事件回调函数
                onRightClick: OnRightClick, //定义节点右键单击事件回调函数
                beforeRename: beforeRename, //定义节点重新编辑成功前回调函数
                onDblClick: onDblClick, //定义节点双击事件回调函数
                onAsyncSuccess: ztreeOnAsyncSuccess, //每次异步获取数据回调函数
                onCheck: onCheck  //定义节点复选框选中或取消选中事件的回调函数
            },
            async: {
                enable: true,   //设置启用异步加载
                type: "post",   //异步加载类型:post和get
                contentType: "application/json", //定义ajax提交参数的参数类型，一般为json格式
                url: '/index.php?m=Admin&c=Organization&a=selectorTree',  //定义数据请求路径
                autoParam: ["id=id"] //定义提交时参数的名称，=号前面标识节点属性，后面标识提交时json数据中参数的名称
            }
        }
    };


    MemberSelector.prototype._init = function(elem,options,callback){
        this._bindEvent(elem,options,callback);
    };

    MemberSelector.prototype._bindEvent = function(elem,options,callback){
        //绑定元素弹出显示事件
        elem.off('click').on('click',function(){
            $(document.body).append(modalhtml);
            $('.modal-content').append(selectorhtml);
            
            $(".Checkbox").change(function() {  /////////////显示无部门的人员
				if($('.Checkbox').is(':checked')){
					var u = 'user';
					var html = "";
			 		$.post("/index.php?m=Admin&c=Userdeprel&a=getNULLuserList",{},function(result){
			 			for(var itme in result){
							html += "<li class='c_list_item'><i class='fa fa-user-plus'></i>&nbsp;<span>&nbsp;</span>&nbsp;<span>"+ result[itme].Name +"</span><i data-id='"+result[itme].ID+"' data-name='"+result[itme].Name+"' data-type='"+u+"' class='iconfonts fa fa-check selector-add'></i></li>";
						}
						$('#user').html(html);
						$('#treeOrg').css("display","none");
						$('.selector-add').off('click').on('click',function(){
			                var id=$(this).data('id');
			                var name = $(this).data('name');
			                var type = $(this).data('type');
			                selectoradd(id,name,this,type);
			            })
				 	});
				}else{
			 		$('#user').html("");
			 		$('#treeOrg').css("display","");
				}
			});  /////////////显示无部门的人员
			
            $('#selector_box_title').text(options.title);
            $('#MemberSelectorModal').data('type',options.type);
            $('#MemberSelectorModal').data('option',JSON.stringify(options));
            $.fn.zTree.init($("#treeOrg"), options.treeSetting);
            $('#MemberSelectorModal').modal('show');
            $('#MemberSelectorModal').off('hidden.bs.modal').on('hidden.bs.modal', function (e) {
                $('#MemberSelectorModal').remove();
            });


            $("#selector-confirm").click(function(){
                var itmeList = $('#selector > li');
                var itemList = new Array();
                for(var i = 0; i < itmeList.length; i++){
                    var id;
                    var isdid = $(itmeList[i]).attr("did");
                    var title = $(itmeList[i]).attr("title");
                    if(isdid != undefined){
                        id = isdid;
                    }else{
                        id = $(itmeList[i]).attr("uid");
                    }
                    var item = {id:id,title:title};
                    itemList.push(item);
                }
                callback && callback(itemList);
                $('#MemberSelectorModal').modal('hide');
            });
        });
    };

    function myonClick(event, treeId, treeNode){
        getuserlist(treeNode.id);
    }

    function getuserlist(nodeid){
        var u = 'user';
        var html = "";
        $.post("/index.php?m=Admin&c=Userdeprel&a=getuserinfo",{id:nodeid},function(result){
            for(var itme in result){
                html += "<li class='c_list_item'><i class='fa fa-user-plus'></i>&nbsp;<span>&nbsp;</span>&nbsp;<span>"+ result[itme].Name +"</span><i data-id='"+result[itme].ID+"' data-name='"+result[itme].Name+"' data-type='"+u+"' class='iconfonts fa fa-check selector-add'></i></li>";
            }
            $('#user').html(html);
            $('.selector-add').off('click').on('click',function(){
                var id=$(this).data('id');
                var name = $(this).data('name');
                var type = $(this).data('type');

                selectoradd(id,name,this,type);
            })
        });
    }

    function selectoradd(id,name,dom,type){

        var option = JSON.parse($('#MemberSelectorModal').data('option'));
        if(!option.multiple){
            if($('#selector > li').length > 0){
                alert('不能选择多个');
                return false;
            }
        }
        switch (option.type){
            case 1:{
                if(type !== "user"){
                    alert('不能选择部门');
                    return false;
                }
            }break;
            case 2:{
                if(type === "user"){
                    alert('不能选择用户');
                    return false;
                }
            }break;
        }
        $(dom).parent().remove();
        if(type == "user"){
            var faicon = "fa fa-user-plus";
            var idtype = "uid";
        }else{
            var faicon = "fa fa-folder-open";
            var idtype = "did";
        }
        type = type+id;
        var html = "<li id='"+ id +"' class='c_list_item "+ type +"' "+ idtype +"='"+ id +"' title='"+ name +"'><i class='"+ faicon  +"'></i>&nbsp;<span>&nbsp;</span>&nbsp;<span>"+ name +"</span><i class='iconfonts fa fa-close selector-delete'></i></li>";
        $('#selector').append(html);
        $('.selector-delete').off('click').on('click',function(){
            $(this).parent().remove();
            selectorcount();
        });
        selectorcount();
        return true;
    }

    function selectorcount(){
        $('#al-selector-count').text($('#selector > li').length);
    }
    function OnRightClick(){}

    function beforeRename(){}

    function onDblClick(){}

    function onCheck(event, treeId, treeNode){
        if(treeNode.checked == false ){
            $('.department'+treeNode.id).remove();
            selectorcount();
        }else{
            if(!selectoradd(treeNode.id,treeNode.name,null,"department")){
                treeNode.checked = false;
            }
        }
    }
    function ztreeOnAsyncSuccess(event, treeId, treeNode){}


    return MemberSelector;
});